const { exec } = require('../db/mysql');
const getList = (auther, keyword) => {
    let sql = `select * from blogs where 1=1 `;
    if(auther) {
        sql += `and author = '${auther}' `;
    }
    if(keyword) {
        sql += `and title like '%${keyword}%' `;
    }
    sql += `order by createtime desc;`
    let data = exec(sql);
    return data;
}
const getDetail = (id) => {
    let sql = `select * from blogs where id = ${id}`;
    let data = exec(sql);
    return data.then(row => {
        return row[0];
    });
}
const newBlog = (blogData = {}) => {
    const time = new Date().getTime();
    const sql = `insert into blogs (auther, title, content, createtime) values ('${blogData.auther}','${blogData.title}', '${blogData.content}', ${time});`;
    return exec(sql).then(res => {
        return res.insertId;
    }); 
}
const updateBlog = (id, blogData = {}) => {
    const time = new Date().getTime();
    const sql = `update blogs set title='${blogData.title}', content='${blogData.content}', createtime='${time}' where id=${id};`;
    return exec(sql).then(res => {
        if(res.affectedRows > 0) {
            return true;
        } else {
            return false;
        }
    });
}
const delBlog = (id) => {
    const sql = `delete from blogs where id='${id}';`;
    return exec(sql).then(res => {
        if(res.affectedRows > 0) {
            return true;
        } else {
            return false;
        }
    });
}
module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    updateBlog,
    delBlog
}